package system

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"jgyApi/server/global"
	"jgyApi/server/model/common/response"
	"jgyApi/server/model/system"
	systemReq "jgyApi/server/model/system/request"
	systemRes "jgyApi/server/model/system/response"
	"jgyApi/server/utils"
	"time"
)

func (b *BaseApi) Login(c *gin.Context) {
	var l systemReq.Login
	err := c.ShouldBind(&l)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(l, utils.LoginVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	u := &system.AuthAdmin{Username: l.Username, Password: l.Password, LastIP: l.LastIp}
	user, err := userService.Login(u)

	if err != nil {
		global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
		// 验证码次数+1
		//global.BlackCache.Increment(key, 1)
		response.FailWithMessage("用户名不存在或者密码错误", c)
		return
	}
	if user.AuthGroupID == 5 {
		user.ID = *user.AssistID
	}
	if *user.Examine == 0 {
		response.FailWithMessage("账号没有通过审核", c)
		return
	}
	if user.Status == 2 {
		response.FailWithMessage("该账号被禁用,请联系管理员", c)
		return
	}

	switch user.LoginStatus {
	case 0: //不在线
		global.GVA_DB.Model(&user).Update("login_status", 1)
		break
	case 1: //在线
	    if user.LastIP != l.LastIp {
			global.GVA_DB.Model(&user).Update("login_status", 2)
		}
		break
	case 2:
		if user.LastIP != l.LastIp {
			global.GVA_DB.Model(&user).Update("login_status", 1)
		}
		break
	}
	details := "登录成功"
	result := global.GVA_DB.Create(&system.AdminLog{Username: l.Username, IP: l.LastIp, Remark: "登录", CreateTime: float64(time.Now().Unix()), Details: &details})
	if result.Error != nil {
		errors.Is(result.Error, gorm.ErrRecordNotFound)
	}
	b.TokenNext(c, *user)
	return

}

// TokenNext 登录以后签发jwt
func (b *BaseApi) TokenNext(c *gin.Context, user system.AuthAdmin) {
	j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
	claims := j.CreateClaims(systemReq.BaseClaims{
		ID:          user.ID,
		Username:    user.Username,
	})
	token, err := j.CreateToken(claims)
	if err != nil {
		global.GVA_LOG.Error("获取token失败!", zap.Error(err))
		response.FailWithMessage("获取token失败", c)
		return
	}
	if !global.GVA_CONFIG.System.UseMultipoint {
		expiresAt := claims.RegisteredClaims.ExpiresAt.Unix() * 1000
		loginResponse := systemRes.SetLoginResponse(user,token,expiresAt)
		response.OkWithDetailed(loginResponse,"登录成功", c)
		return
	}

	//if jwtStr, err := jwtService.GetRedisJWT(user.Username); err == redis.Nil {
	//	if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
	//		global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
	//		response.FailWithMessage("设置登录状态失败", c)
	//		return
	//	}
	//	response.OkWithDetailed(systemRes.LoginResponse{
	//		User:      user,
	//		Token:     token,
	//		ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
	//	}, "登录成功", c)
	//} else if err != nil {
	//	global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
	//	response.FailWithMessage("设置登录状态失败", c)
	//} else {
	//	var blackJWT system.JwtBlacklist
	//	blackJWT.Jwt = jwtStr
	//	if err := jwtService.JsonInBlacklist(blackJWT); err != nil {
	//		response.FailWithMessage("jwt作废失败", c)
	//		return
	//	}
	//	if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
	//		response.FailWithMessage("设置登录状态失败", c)
	//		return
	//	}
	//	response.OkWithDetailed(systemRes.LoginResponse{
	//		User:      user,
	//		Token:     token,
	//		ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
	//	}, "登录成功", c)
	//}
}
